import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import { getAuthAxios } from '../lib/authAxios.js';
import axios from '../lib/axios.min.js';

import { message } from 'antd';
// 环节添加图片
const RootComponent = () => {
  var dataObj;
  const myAxios = getAuthAxios();
  useEffect(() => {
    dataObj = window.getMyGlobalVar('warningObj');
    function onGlobalVarChange(e) {
      if (['营业厅受理', '上门服务'].includes(window.getMyGlobalVar('activeTabName'))) {
        initImgAddPage();
      } else {
        removeImgbtn()
      }
      dataObj = window.getMyGlobalVar('warningObj');
    }
    window.addEventListener('MY_GLOBAL_VAR_CHANGE', onGlobalVarChange);
    return () => window.removeEventListener('MY_GLOBAL_VAR_CHANGE', onGlobalVarChange);
  }, []);
  const initImgAddPage = () => {
    handleBtn(document.body);
  };

  const removeImgbtn = () => {
    const pdom = document.body
    let addDom = pdom.querySelector('#_addimg')
    addDom && addDom.remove()
    let viewDom = pdom.querySelector('#_viewimg')
    viewDom && viewDom.remove()
  }

  const handleBtn = pdom => {
    // 检查按钮是否已存在
    if (pdom.querySelector('#_addimg') || pdom.querySelector('#_viewimg')) {
      return;
    }

    // 创建添加图片按钮
    const addBtn = document.createElement('button');
    addBtn.style.position = 'absolute';
    addBtn.style.top = '65px';
    addBtn.style.right = '120px';
    addBtn.style.zIndex = '999';
    addBtn.style.backgroundColor = '#4caf50';
    addBtn.style.color = 'white';
    addBtn.style.border = 'none';
    addBtn.style.padding = '8px 20px';
    addBtn.style.cursor = 'pointer';
    addBtn.textContent = '添加图片';
    addBtn.style.borderRadius = '5px';
    addBtn.style.opacity = '0.9';
    addBtn.id = '_addimg';

    // 创建查看图片按钮
    const viewBtn = document.createElement('button');
    viewBtn.style.position = 'absolute';
    viewBtn.style.top = '65px';
    viewBtn.style.right = '20px';
    viewBtn.style.zIndex = '999';
    viewBtn.style.backgroundColor = '#2196f3';
    viewBtn.style.color = 'white';
    viewBtn.style.border = 'none';
    viewBtn.style.padding = '8px 20px';
    viewBtn.style.cursor = 'pointer';
    viewBtn.textContent = '查看图片';
    viewBtn.style.borderRadius = '5px';
    viewBtn.style.opacity = '0.9';
    viewBtn.id = '_viewimg';

    // 添加图片按钮点击事件 - 上传图片
    addBtn.addEventListener('click', async () => {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      input.multiple = false;

      input.onchange = async e => {
        if (e.target && e.target.files && e.target.files.length > 0) {
          console.log(e.target.files)
          const file = e.target.files[0]
          console.log('file', file)
          if (!file) return
          const formData = new FormData();
          formData.append('file', file);
          formData.append('workOrderNo', dataObj.workOrderNo);
          formData.append('processName', dataObj.processName);
          formData.append('nodeName', dataObj.nodeName);
          // formData.append('signUser', dataObj.signUser);
          formData.append('countyName', dataObj.countyName);
          formData.append('supplyUnit', dataObj.supplyUnit);

          console.log(formData.get("file").name)

          try {
            const response = await myAxios.post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcPhotoAddon', formData);
            console.log(response)
            if (response.data.data) {
              message.success('图片上传成功');
            } else {
              console.error('图片上传失败: ' + response.data.message);
            }
          } catch (error) {
            console.error('上传接口调用失败: ' + error.message);
          }
        }
      }
      input.click();
    });

    // 查看图片按钮点击事件 - 显示图片预览弹窗
    viewBtn.addEventListener('click', async () => {
      try {
        // 调用接口获取图片列表
        const response = await myAxios.post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcPhotoAddon/list', {});
        const images = response.data.data.list || [];
        if (images.length === 0) {
          message.info('暂无图片数据');
          return;
        }

        // 创建弹窗容器
        const modalDiv = document.createElement('div');
        // 创建关闭按钮
        const closeBtn = document.createElement('div');
        closeBtn.style.position = 'absolute';
        closeBtn.style.top = '10px';
        closeBtn.style.right = '10px';
        closeBtn.style.fontSize = '20px';
        closeBtn.style.cursor = 'pointer';
        closeBtn.textContent = '×';
        closeBtn.style.color = '#999';
        closeBtn.style.width = '20px';
        closeBtn.style.height = '20px';
        closeBtn.style.textAlign = 'center';
        closeBtn.style.lineHeight = '20px';
        closeBtn.style.borderRadius = '50%';

        // 点击关闭按钮关闭弹窗
        closeBtn.addEventListener('click', () => {
          document.body.removeChild(modalDiv);
          document.removeEventListener('click', closeModal);
        });

        modalDiv.appendChild(closeBtn);
        modalDiv.style.position = 'fixed';
        modalDiv.style.left = '20px';
        modalDiv.style.top = '50%';
        modalDiv.style.transform = 'translateY(-50%)';
        modalDiv.style.width = '350px';
        modalDiv.style.height = '500px';
        modalDiv.style.backgroundColor = 'white';
        modalDiv.style.borderRadius = '8px';
        modalDiv.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';
        modalDiv.style.zIndex = '1000';
        modalDiv.style.padding = '15px';
        modalDiv.id = 'imagePreviewModal';

        // 创建标题
        const title = document.createElement('div');
        title.style.fontSize = '16px';
        title.style.fontWeight = 'bold';
        title.style.marginBottom = '15px';
        title.style.textAlign = 'center';
        title.textContent = '图片预览';
        modalDiv.appendChild(title);

        // 创建图片容器（带滚动条）
        const imgContainer = document.createElement('div');
        imgContainer.style.height = 'calc(100% - 40px)';
        imgContainer.style.overflowY = 'auto';
        imgContainer.style.display = 'flex';
        imgContainer.style.flexDirection = 'column';
        imgContainer.style.gap = '10px';

        // 添加图片到容器
        images.forEach((img, index) => {
          const imgDiv = document.createElement('div');
          imgDiv.style.textAlign = 'center';

          const imgElement = document.createElement('img');
          imgElement.src = img.url;
          imgElement.alt = '图片 ' + (index + 1);
          imgElement.style.maxWidth = '100%';
          imgElement.style.maxHeight = '150px';
          imgElement.style.borderRadius = '4px';
          imgElement.style.cursor = 'pointer';

          // 添加下载按钮
          const downloadBtn = document.createElement('button');
          downloadBtn.textContent = '下载';
          downloadBtn.style.marginTop = '5px';
          downloadBtn.style.marginLeft = '15px';
          downloadBtn.style.padding = '5px 10px';
          downloadBtn.style.backgroundColor = '#ff9800';
          downloadBtn.style.color = 'white';
          downloadBtn.style.border = 'none';
          downloadBtn.style.borderRadius = '4px';
          downloadBtn.style.cursor = 'pointer';
          downloadBtn.style.fontSize = '12px';

          // 点击下载按钮调用接口下载图片
          downloadBtn.addEventListener('click', async () => {
            try {
              // 假设接口需要图片id，这里从img对象中获取
              const imageId = img.id;
              const imgName = img.photoName
              const response = await myAxios.post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcPhotoAddon/download', {id:imageId}, {
                responseType: 'blob'
              });
              // console.log("xiazai",response)
              download(response,imgName)
              return
              // 创建下载链接
              const url = window.URL.createObjectURL(new Blob([response.data]));
              const link = document.createElement('a');
              link.href = url;
              // 从图片url中提取文件名作为下载文件名
              const fileName = img.url.split('/').pop();
              link.setAttribute('download', fileName);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url);
            } catch (error) {
              console.error('图片下载失败: ' + error.message);
            }
          });



          // 点击图片可查看大图
          imgElement.onclick = () => {
            // 这里可以实现大图预览逻辑
            const largeImgModal = document.createElement('div');
            largeImgModal.style.position = 'fixed';
            largeImgModal.style.top = '0';
            largeImgModal.style.left = '0';
            largeImgModal.style.width = '100%';
            largeImgModal.style.height = '100%';
            largeImgModal.style.backgroundColor = 'rgba(0,0,0,0.8)';
            largeImgModal.style.zIndex = '1001';
            largeImgModal.style.display = 'flex';
            largeImgModal.style.alignItems = 'center';
            largeImgModal.style.justifyContent = 'center';

            const largeImg = document.createElement('img');
            largeImg.src = img.url;
            largeImg.style.maxWidth = '90%';
            largeImg.style.maxHeight = '90%';

            largeImgModal.appendChild(largeImg);
            document.body.appendChild(largeImgModal);

            // 点击大图模态框关闭
            largeImgModal.onclick = () => {
              document.body.removeChild(largeImgModal);
            };
          };

          imgDiv.appendChild(imgElement);
          imgDiv.appendChild(downloadBtn);
          imgContainer.appendChild(imgDiv);
        });

        modalDiv.appendChild(imgContainer);
        document.body.appendChild(modalDiv);

        // 点击弹窗外部关闭
        const closeModal = e => {
          if (e.target.id === 'imagePreviewModal') {
            document.body.removeChild(modalDiv);
            document.removeEventListener('click', closeModal);
          }
        };
        document.addEventListener('click', closeModal);
      } catch (error) {
        message.error('获取图片列表失败: ' + error.message);
      }
    });

    pdom.appendChild(addBtn);
    pdom.appendChild(viewBtn);
  };
  function download(res,imgName) {
    if (res.status === 200) {
      let bold = res.data
      let reader = new FileReader()
      // console.log("dddddd",res.headers)
      // let name = res.headers['content-disposition']?.match(/fileName=.*/)[0]
      // name = name.replace('fileName=', '') ||"图.png"
      let name = imgName 
      reader.readAsDataURL(bold)
      reader.onload = (e) => {
        let a = document.createElement('a')
        document.body.appendChild(a)
        a.download = decodeURIComponent(name)
        a.href = e.target.result
        a.click()
        document.body.removeChild(a)
      }
    } else {
      console.error('下载任务出错，请联系平台')
    }
  }
  return null;
};

const init = () => {
  if (document.getElementById('self-div-img')) {
    return;
  }
  const container = document.createElement('div');
  container.id = 'self-div-img';
  container.style.fontSize = '14px';
  document.body.appendChild(container);
  const root = ReactDOM.createRoot(container);
  root.render(<RootComponent />);
};

init();
